package edu.dali.enterprise_test.config.shiro.realm;

import edu.dali.enterprise_test.model.vo.Dto;
import edu.dali.enterprise_test.model.vo.SysPermission;
import edu.dali.enterprise_test.model.vo.SysRole;
import edu.dali.enterprise_test.model.vo.UserInfo;
import edu.dali.enterprise_test.service.auth.AuthService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private AuthService authService;
    /**
     * 权限认证
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //这是shiro提供的.
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //获取到用户的权限信息.
        UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal();
        for(SysRole role:userInfo.getRoles()){
            //添加角色.
            authorizationInfo.addRole(role.getRole());
            //添加权限.
            for(SysPermission p:role.getPermissions()){
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        Dto dto = new Dto();
        dto.put("username" , username);
        UserInfo userInfo = authService.selectUser(dto);

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), ByteSource.Util.bytes(userInfo.getSalt()), getName());

        //4、返回身份处理对象.
        return simpleAuthenticationInfo;
    }
}
